const fs = require('fs')
const path = require('path')
const mongoose = require('mongoose')

function load(dir, cb) {
    const url = path.resolve(__dirname,dir)
    const files = fs.readFileSync(url)
    files.forEach(filename => {
        filename = filename.repalce('.js', '')
        const file = require(url + '/' + filename)
        cb(filename, file)
    })
}

const loadModel = config=> app=> {
    mongoose.connect(config.db.url, conf.db.options)
    const conn = mongoose.connection
    conn.on('error',()=> {console.error('数据库连接失败')})
    app.$model = {}
    load('../model',(filename,{schema}) => {
        console.log("连接model")
        app.$model[filename] = mongoose.model(filename,schema)
    })
}

module.exports = {
    loadModel
}
